<?php

namespace app\api\controller;

use app\BaseController;
use think\facade\Db; // 数据库的链接


class Card extends BaseController
{
    // 获取卡片列表
    public function getCardList()
    {
        $data = Db::name('card')->field('id,image,name,price')->where('del',0)->order('sort','asc')->select()->toArray();
        return json(['code' => 200,'msg' => '获取成功', 'data' => $data]);
    }

    // 获取单张卡片信息
    public function getCardInfo()
    {
        $data = input();
        $id = $data['id'];
        $card = Db::name('card')->where('id', $id)->where('del',0)->find();
        if (!$card) {
            return json(['code' => 500,'msg' => '闪卡不存在']);
        }
        return json(['code' => 200,'msg' => '获取成功', 'data' => $card]);
    }

    // 用户与用户之间互相添加卡片
    /**
     * @param card_id 卡片id
     * @param user_id 用户id
     * @param num 数量 用户端一次性赠送一张卡片，所以数量默认为1
     */
    public function addCard()
    {
        $data = input();
        $cid = $data['cid'];
        $sid = $data['sid'];
        $num = @$data['num']?? 1;

        if($num > 1){
            return json(['code' => 500,'msg' => '一次只能赠送一张闪卡']);
        }

        // 获取被赠送用户的信息 并且判断是否存在

        $suser = Db::name('user')->where('id', $sid)->find();
        if (!$suser) {
            return json(['code' => 500,'msg' => '收卡用户不存在']);
        }

        // 获取用户信息
        $UID = request()->UID;
        $user = Db::name('user')->where('id', $UID)->find();
        // 判断用户有没有权限赠送卡片
        if ($user['is_shopowner']!= 1) {
            return json(['code' => 500,'msg' => '无权限']);
        }
       
        // 随机查询1张当前用户未使用的闪卡
        $card = Db::name('user_card_record')->where('uid', $UID)->where('cid', $cid)->where('is_status',0)->orderRaw('rand()')->find();
        
        // 判断是否有闪卡
        if (!$card) {
            return json(['code' => 500,'msg' => '没有可赠送的闪卡']);
        }
        // 判断闪卡是否存在 没有删除的闪卡
        $card_info = Db::name('card')->where('id', $card['cid'])->where('del',0)->find();
        if (!$card_info) {
            return json(['code' => 500,'msg' => '闪卡不存在']);
        }
        
        // 开启事务
        Db::startTrans();
        try {
            // 扣除用户的闪卡数量
            $this->updateCard($uid,$card['id'],1,'赠送给用户ID:'.$sid.'的闪卡');
            
            // Db::name('user_card_record')->where('id', $card['id'])->update(['is_status' => 1,'del' => 1,'usage_time' => time(),'end_time' => time(),'remark' => ]);
            
            // 调用common方法，给被赠送用户添加卡片
            $res = flashCardSend($sid, $card_info['id'], $num,'来着用户ID:'.$UID.'的赠送');
            if ($res['code']!= 200) {
                return $res;

            }
            // 提交事务
            Db::commit();
            return json(['code' => 200,'msg' => '赠送成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500,'msg' => '赠送失败']);
        }
    }
    /**
     * 更新卡片信息
     * @param uid 用户id
     * @param card_id 卡片id
     * @param del 状态 0使用中 1失效
     * @param remark 备注
    */
    public function updateCard($uid,$card_id,$del,$remark)
    {
        $data = [
            'remark' => $remark,
            'del' => $del,
            'is_status' => 1,
            'usage_time' => time(),
        ];

        if($del == 1){
            $data['end_time'] = time();
        }else{
            // 获取去当前数据
            $user_card_record = Db::name('user_card_record')->where('id', $card_id)->find();

            // 获取闪卡信息
            $card_info = Db::name('card')->where('id', $user_card_record['cid'])->find();

            // 获取过期时间戳

            $end_time = strtotime("+{$card_info['duration']} day");

            $data['end_time'] = $end_time;
        }
        $res = Db::name('user_card_record')->where('id',$card_id)->where('uid', $uid)->update($data);
        if($res){
            return array('code' => 200,'msg' => '更新成功');
        }else{
            return array('code' => 500,'msg' => '更新失败');
        }
    }

    // 使用闪卡
    public function useCard()
    {
        $data = input();
        $cid = $data['cid']; // 闪卡id
        $UID = request()->UID;
        // 开启事务

        $card = Db::name('user_card_record')->where('uid', $UID)->where('cid', $cid)->where('is_status',0)->orderRaw('rand()')->find();
        if (!$card) {
            return json(['code' => 500,'msg' => '没有可使用的闪卡']);
        }
        
        //同一个类型的闪卡只能使用一次
        
        $count = Db::name('user_card_record')->where('uid', $UID)->where('cid', $cid)->where('is_status',1)->where('del',0)->count();
        if ($count > 0) {
            return json(['code' => 500,'msg' => '同一类型的闪卡只能使用一次']);
        }

        Db::startTrans();
        try {
            // user_card_record 表的$card['id'] 是 id 不是闪卡id
            $res =$this->updateCard($UID,$card['id'],0,'使用闪卡');
            if ($res['code']!= 200) {
                return $res;
            }
            // 提交事务
            Db::commit();
            return json(['code' => 200,'msg' => '使用成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500,'msg' => '使用失败']);
        }
    }
    // 查询闪卡的使用记录 只包含使用中的闪卡 1收益 和2停止收益
    public function getCardRecord()
    {
        $data = input();
        $UID = request()->UID;
        $type = $data['type']?? 1; // 1收益 2停止收益
        $page = $data['page']?? 1;
        $limit = $data['limit']?? 10;
        $where = [];
        $where[] = ['a.uid', '=', $UID];
        $where[] = ['a.is_status', '=', 1];
        if($type == 1){
            $where[] = ['a.del', '=', 0];
        }else{
            $where[] = ['a.del', '=', 1];
        }
        
        $list = Db::name('user_card_record')
            ->alias('a')
            ->join('card b', 'a.cid = b.id')
            ->where($where)
            ->field("a.*,b.name,b.image,FROM_UNIXTIME(a.obtain_time,'%Y-%m-%d %H:%i:%s') as obtain_time,FROM_UNIXTIME(a.usage_time,'%Y-%m-%d %H:%i:%s') as usage_time,FROM_UNIXTIME(a.end_time,'%Y-%m-%d %H:%i:%s') as end_time")
            ->order('a.end_time', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])
            ->toArray();
        // 返回数据
        return json(['code' => 200,'data' => $list,'msg' => '获取成功']);
    }
    /**
     * 签到领取闪卡的收益 多张闪卡
     */
    public function signCard()
    {
        $UID = request()->UID;

         // 查询收益时间小于今日的数据
         $today = date('Y-m-d');
         $where = ['profit_time' => ['lt', $today]];

        // 查询用户是否有闪卡
        $count = Db::name('user_card_record')->where('uid', $UID)->where($where)->where('is_status',1)->where('del',0)->count();
        if ($count == 0) {
            return json(['code' => 500,'msg' => '没有可领取的收益']);
        }

        // 开启事务
        Db::startTrans();
        try {
            // 查询用户的闪卡
            $cards = Db::name('user_card_record')->where('uid', $UID)->where($where)->where('is_status',1)->where('del',0)->select();
            // 遍历闪卡
            foreach ($cards as $key => $value) {
                // 当前时间是否小于结束时间
                if (time() < $value['end_time']) {
                    // 领取收益
                    // 查询对应的闪卡
                    $card_info = Db::name('card')->where('id', $value['cid'])->find();
                    // 自己领取收益
                    userRecord($UID, $card_info['day'],1,0,'签到'.$card_info['name'].'收益领取');

                    // 团队收益
                    getMiningProfitByParent($UID, $card_info['day'], 1, '签到'.$card_info['name'].'收益领取');

                    // 更新闪卡记录
                    if ($value['profit_day'] + 1 == $card_info['duration']) {
                        // 更新闪卡收益结束
                        Db::name('user_card_record')->where('id', $value['id'])->update(['is_status' => 1,'del' => 1,'end_time' => time(),'profit_day' =>$value['profit_day'] + 1,'profit_time' => time(),'remark' => '使用闪卡收益到期']);
                    }else{
                        // 更新闪卡 收益中
                        Db::name('user_card_record')->where('id', $value['id'])->update(['profit_day' => $value['profit_day'] + 1,'profit_time' => time()]);
                    }
                }else{
                    // 闪卡已过期 -- 更新闪卡不再收益
                    Db::name('user_card_record')->where('id', $value['id'])->update(['is_status' => 1,'del' => 1,'end_time' => time(),'profit_day' => $value['profit_day'],'profit_time' => time(),'remark' => '使用闪卡收益到期']);
                }
            }

            Db::commit();
            return json(['code' => 200,'msg' => '领取成功']);
            // 提交事务
            
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['code' => 500,'msg' => '领取失败']);
        }
    }
}